import Vue from 'vue'
import VueRouter from 'vue-router'

const login = () => import('../components/login/login')
const home = () => import('../components/home/home')
const welcome = () => import('../components/welcome/welcome')
const users = () => import('../components/users/users')
const rightsList = () => import('../components/rights/rightsList')
const roles = () => import('../components/roles/roles')

const cate = () => import('../components/goods/cate')
const params = () => import('../components/goods/params')
const list = () => import('../components/goods/list')
const add = () => import('../components/goods/add')
const order = () => import('../components/order/order')
const report = () => import('../components/report/report')
const edit = () => import('../components/goods/edit')


Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:'/login'
  },
  {
    path:'/login',
    component:login
  },
  {
    path:'/home',
    component:home,
    redirect:'/welcome',
    children:[
      {
        path:'/welcome',
        component:welcome
      },
      {
        path:'/users',
        component:users
      },
      {
        path:'/rights',
        component:rightsList
      },
      // 角色列表
      {
        path:'/roles',
        component:roles
      },
      {
        path:'/categories',
        component:cate
      },
      {
        path:'/params',
        component:params
      },
      {
        path:'/goods',
        component:list
      },
      {
        path:'/good/add',
        component:add
      },
      {

        path:'/orders',
        component:order
      },
      {
        path:'/reports',
        component:report
      },
        {
        path:'/good/edit',
        name:'edit',
        component:edit
        }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 使用路由导航守卫 对进入主页进行 进行控制
router.beforeEach((to,from,next) => {
  // to --- 是要跳转到的路由
  // form --- 是 从哪里跳转过来的路由
  // next --- 放行函数
  // next() 直接放行 next('/login') 里面存放的是路由的话，表示强制跳转
  if(to.path === '/login') {
    // 要跳转到 登录页面的话就直接放行
    return next()
  }

  //如果不是跳转到 登录页面 先判断 sessionstorage 中有没有 登录成功返回的 token 
  const tokenStr = window.sessionStorage.getItem('token')
  if(!tokenStr) {
    //没有 token 值 说明还没有登录 需要强制跳转到登录页面
    return next('/login')
  }

  //没有问题 直接放行
  next()
})
export default router
